package com.xcc.dataStructures.leetcode;

import java.util.*;

/**
 * 根据字符出现的频率重新排列字符串
 * happy——>pphay
 */
public class Demo013_RateCharsByString {

    public static void main(String[] args) {
        String s = "happy";
        char[] chars = s.toCharArray();

        LinkedHashMap<Character, Integer> map = new LinkedHashMap<>();
        for (char aChar : chars) {
            map.put(aChar, map.get(aChar) == null ? 1 : map.get(aChar) + 1);
        }

        List<Word> words = new ArrayList<>();
        for (Map.Entry<Character, Integer> entry : map.entrySet()) {
            words.add(new Word(entry.getKey(), entry.getValue()));
        }
        Collections.sort(words);

        StringBuffer sb = new StringBuffer();
        for (Word word : words) {
            for (int i = 0; i < word.count; i++) {
                sb.append(word.aChar);
            }
        }
        System.out.println(sb.toString());

    }

    static class Word implements Comparable<Word>{
        char aChar;
        int count;

        public Word(char aChar, int count) {
            this.aChar = aChar;
            this.count = count;
        }

        @Override
        public int compareTo(Word o) {
            return o.count - this.count;
        }

        @Override
        public String toString() {
            return "Word{" +
                    "aChar=" + aChar +
                    ", count=" + count +
                    '}';
        }
    }
}
